package com.enlorenz.common.excel;

import java.io.IOException;
import java.io.OutputStream;

import com.enlorenz.common.util.CommonContants;
import com.enlorenz.common.util.StreamUtils;

/**
 * CSV导出
 * @author Karma
 */
public class DataExporter4Csv<T> extends AbstractDataExporter<T>{
	private StringBuilder stringBuilder=new StringBuilder();
	public static final String VALUE_SPLITOR=",";
	//字符编码
	private String encoding="gbk";
	
	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}
	public DataExporter4Csv(Class<T> dataClass){
		super(dataClass);
	}
	
	public DataExporter4Csv(){
	}
	
	@Override
	protected void doHeadValue(int colIndex,int colSize,DataHeadParam dataHeadParam) {
		stringBuilder.append(dataHeadParam.getProperty().name());
		if(colIndex != colSize-1){
			stringBuilder.append(VALUE_SPLITOR);
		}
	}

	@Override
	protected void doDataValue(int rowIndex,int rowSize,int colIndex,int colSize,String dataValue) {
		if(0 == colIndex){
			stringBuilder.append(CommonContants.WRAP_SYMBOL);
		}
		stringBuilder.append(dataValue);
		if(colIndex != colSize-1){
			stringBuilder.append(VALUE_SPLITOR);
		}
	}
	

	public String getResult(){
		return stringBuilder.toString();
	}

	@Override
	protected void writeOutputStream(OutputStream outputStream) {
		try {
			outputStream.write(getResult().getBytes(encoding));
			outputStream.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			StreamUtils.closeStream(outputStream);
		}
	}

}
